import os
import uuid
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from .image_process.filter import ImageFilter
from .image_process.hist_euqal import equalizeHistImage
from .image_process.feature import FeatureExtract
from .image_process.svmModel import svmPrect
from .image_process.bpModel import preBpNetwork
from django.views.decorators.csrf import csrf_exempt
from .image_process.color_component import show_Rcomponent,show_Gcomponent,\
    show_Bcomponent,show_Hcomponent,show_Scomponent,show_Vcomponent,show_gray
# Create your views here.

# @login_required(login_url='/login')
@csrf_exempt
def index(request):
    return render(request, 'deal/index.html')
    # return HttpResponse("Hello World. You're at the index")

@csrf_exempt
def upload(request):
    if request.method == "POST":
        upload_file = request.FILES.get('file')
        if not upload_file:
            return JsonResponse({"code": 400, "message": "文件不存在"})
        else:
            # 后缀
            suffix_file = upload_file.name.split(".")[-1]
            # 文件名
            file_name = str(uuid.uuid1()) + "." + suffix_file
            # 文件上传位置
            upload_dir = os.path.join(settings.UPLOAD_DIR)
            # 读取文件到内存
            destination = open(os.path.join(upload_dir, file_name), 'wb+')
            # 块保存在硬盘中
            for chunk in upload_file.chunks():
                destination.write(chunk)
            # 释放内存
            destination.close()
            return JsonResponse({"code": 200, "message": "upload/"+file_name})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})


# 登录
@csrf_exempt
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # user = User.objects.filter(username=username).first()
        # res = check_password(password, user.password)
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            auth.login(request, user)
            return redirect('/')
        else:
            return render(request, 'login.html', {"code": 400,"message": "账号或者密码错误"})

    else:
        return JsonResponse({"code": 400, "message": "方法错误"})


# 注册
@csrf_exempt
def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        repassword = request.POST.get('repassword')
        email = request.POST.get('email')
        if password != repassword:
            return render(request, 'deal/register.html')
        names = User.objects.filter(username=username).first()
        if names:
            return JsonResponse({"code": 400, "message": "用户名已经存在"})
        emails = User.objects.filter(email=email).first()
        if emails:
            return JsonResponse({"code": 400, "message": "email已经存在"})
        # 注册用户 return user
        User.objects.create_user(username=username, password=password, email=email, is_superuser=1, is_staff=1)
    return JsonResponse({"code": 200, "message": "注册成功"})


# 注销
@csrf_exempt
def logout(request):
    try:
        auth.logout(request)
    except Exception as e:
        print(e)
    return render(request, 'deal/register.html')


# 读取全部文件
# @login_required(login_url='/login')
@csrf_exempt
def read(request):
    file_dir = settings.UPLOAD_DIR
    file_list = os.listdir(file_dir)
    # for filename in os.listdir(file_dir):
    #     print(filename)
    return render(request, 'deal/read.html', {"file_list": file_list})

@csrf_exempt
def remove(request, img):
    path_dir = settings.UPLOAD_DIR
    os.remove(path_dir + "/" + img)
    return redirect('/read')


# 均值滤波
@csrf_exempt
def avgfilter(request):
    if request.method == "POST":
        filename = request.POST.get('filename')
        imgfilter = ImageFilter()
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir, filename)
            file_name_new = imgfilter.avgImageFilter(path)
            return JsonResponse({"code": 200, "message": "deal/"+file_name_new})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})


# 中值滤波
@csrf_exempt
def medianfilter(request):
    if request.method == "POST":
        filename = request.POST.get('filename')
        imgfilter = ImageFilter()
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir, filename)
            file_name_new = imgfilter.medianImageFilter(path)
            return JsonResponse({"code": 200, "message": "deal/"+file_name_new})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})


# 高斯滤波
@csrf_exempt
def gaussianfilter(request):
    if request.method == "POST":
        filename = request.POST.get('filename')
        imgfilter = ImageFilter()
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir, filename)
            file_name_new = imgfilter.medianImageFilter(path)
            return JsonResponse({"code": 200, "message": "deal/"+file_name_new})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})



# 显示灰度图像
@csrf_exempt
def show_gray_image(request):
    if request.method == "POST":
        filename = request.POST.get("filename")

        try:

            upload_dir = os.path.join(settings.UPLOAD_DIR)
            path = os.path.join(upload_dir,filename)
            file_name_new = show_gray(path)
            return JsonResponse({"code": 200, "message": "deal/"+file_name_new})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})


# 显示R分量
@csrf_exempt
def show_r_compontent(request):
    if request.method == "POST":
        filename = request.POST.get("filename")
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir,filename)
            file_name_new = show_Rcomponent(path)
            return JsonResponse({"code": 200, "message": "deal/"+file_name_new})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})

# 显示G分量
@csrf_exempt
def show_g_compontent(request):

    if request.method == "POST":
        filename = request.POST.get("filename")
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir,filename)
            file_name_name = show_Gcomponent(path)
            return JsonResponse({"code": 200, "message": "deal/"+file_name_name})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})

# 显示B分量
@csrf_exempt
def show_b_compontent(request):
    if request.method == "POST":
        filename = request.POST.get("filename")
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir, filename)
            file_name_new = show_Bcomponent(path)
            return JsonResponse({"code": 200, "message": "deal/"+file_name_new})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})

# 显示H分量
@csrf_exempt
def show_h_compontent(request):

    if request.method == "POST":
        filename = request.POST.get("filename")
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir, filename)
            file_name_name = show_Bcomponent(path)
            return JsonResponse({"code": 200, "message": "deal/"+file_name_name})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})

# 显示S分量
@csrf_exempt
def show_s_compontent(request):
    if request.method == "POST":
        filename = request.POST.get("filename")
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir, filename)
            file_name_new = show_Bcomponent(path)
            return JsonResponse({"code": 200, "message": "deal/"+file_name_new})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})

# 显示V分量
@csrf_exempt
def show_v_compontent(request):
    if request.method == "POST":
        filename = request.POST.get("filename")
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir, filename)
            file_name_new = show_Bcomponent(path)
            return JsonResponse({"code": 200, "message": "deal/"+file_name_new})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})

# 直方图均衡化
@csrf_exempt
def histequal(request):
    # 拼接本地地址
    if request.method == "POST":
        filename = request.POST.get("filename")
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir, filename)
            file_name_new = equalizeHistImage(path)
            return JsonResponse({"code": 200, "message": "deal/"+ file_name_new})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
            #
            # upload_dir = os.path.join(settings.UPLOAD_DIR)
            # path = os.path.join(upload_dir, r'3b50b254-458d-11e9-9174-e86a6420dfa7.JPG')
            # equalizeHistImage(path)
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})

# 形状特征提取
@csrf_exempt
def extract_feature(request):
    if request.method == "POST":
        filename = request.POST.get("filename")
        extractfutre = FeatureExtract()
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir, filename)
            data = extractfutre.huInvariantMoment(path)
            return JsonResponse({"code": 200, "message": [data]})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})


# 颜色特征提取
@csrf_exempt
def color_extract(request):
    if request.method == "POST":
        filename = request.POST.get("filename")
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir, filename)
            extractfutre = FeatureExtract()
            data = extractfutre.colorExtract(path)
            return JsonResponse({"code": 200, "message": [data]})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})



# svm检测
@csrf_exempt
def svm_detection(request):
    if request.method == "POST":
        # 输入图片的的名称
        fileanme = request.POST.get("filename")
        # 输入模型
        save_model = request.POST.get("save_model")     #   /image_deal/static/model/svmModel.h5
        try:
            save_dir = os.path.join(settings.MODEL_DIR)
            upload_dir = os.path.join(settings.UPLOAD_DIR)

            path = os.path.join(upload_dir,fileanme)
            model_path = os.path.join(save_dir,save_model)
            data= svmPrect(model_path,path)
            return JsonResponse({"code": 200, "message": [data]})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})


# BP神经网络检测
@csrf_exempt
def bp_detection(request):
    if request.method == "POST":
        # 输入图片的的名称
        fileanme = request.POST.get("filename")
        # 输入模型
        save_model = request.POST["save_model"]     #/image_deal/static/model/bpModel.h5

        save_dir = os.path.join(settings.MODEL_DIR)
        upload_dir = os.path.join(settings.UPLOAD_DIR)
        try:
            path = os.path.join(upload_dir, fileanme)
            model_path = os.path.join(save_dir, save_model)
            data = preBpNetwork(path, model_path)
            return JsonResponse({"code": 200, "message": [data]})
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "message": "发生错误"})
    else:
        return JsonResponse({"code": 400, "message": "方法错误"})













